﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

using Lenovo.CFI.Common.Sys;
using Lenovo.CFI.Common;

namespace Lenovo.CFI.DAL.Sys
{
    public class UserDa
    {
        public static User GetUserByItCode(string itcode)
        {
            Database db = DBHelper.GetDatabase();

            DbCommand dbCommand = db.GetStoredProcCommand("Usp_GetSysUserByItCode", itcode.ToLower());

            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                if (dataReader.Read())
                {
                    return PopulateUser(dataReader);
                }
            }

            return null;
        }

        public static List<User> GetUserByItCode(params string[] itcodes)
        {
            Database db = DBHelper.GetDatabase();

            DbCommand dbCommand = db.GetStoredProcCommand("Usp_GetSysUserByItCodes", InHelper.ConvertToInStr(itcodes));

            List<User> users = new List<User>();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    users.Add(PopulateUser(dataReader));
                }
            }

            return users;
        }

        public static List<User> GetUserAll()
        {
            Database db = DBHelper.GetDatabase();

            DbCommand dbCommand = db.GetStoredProcCommand("Usp_GetSysUserAll");

            List<User> users = new List<User>();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    users.Add(PopulateUser(dataReader));
                }
            }

            return users;
        }

        /// <summary>
        /// 获取具有指定角色的用户
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public static List<User> GetUserWithRole(int role)
        {
            Database db = DBHelper.GetDatabase();

            DbCommand dbCommand = db.GetStoredProcCommand("Usp_GetSysUserWithRole", role.ToString());

            List<User> users = new List<User>();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    users.Add(PopulateUser(dataReader));
                }
            }

            return users;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="itcode">模糊匹配</param>
        /// <param name="teamID">NULL表示不限制</param>
        /// <param name="manager">NULL表示不限制</param>
        /// <param name="vp">NULL表示不限制</param>
        /// <param name="enabled">NULL表示不限制</param>
        /// <param name="permLevel">NULL表示不限制</param>
        /// <returns></returns>
        public static List<User> GetUser(string itcode, int? teamID, string manager, string vp, bool? enabled, int? permLevel)
        {
            Database db = DBHelper.GetDatabase();

            DbCommand dbCommand = db.GetStoredProcCommand("Usp_GetSysUser", itcode, teamID, manager, vp, enabled, permLevel);

            List<User> users = new List<User>();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    users.Add(PopulateUser(dataReader));
                }
            }

            return users;
        }


        internal static User PopulateUser(IDataReader dataReader)
        {
            User user = new User(dataReader.GetString(0), dataReader.GetString(3), 
                dataReader.IsDBNull(8) ? null : dataReader.GetString(8),
                dataReader.IsDBNull(9) ? null : dataReader.GetString(9));

            user.RealName = dataReader.GetString(1);
            user.Phone = dataReader.GetString(2);
            user.PermLevel = dataReader.GetInt32(4);
            user.Enabled = dataReader.GetBoolean(5);
            if (!dataReader.IsDBNull(6)) user.Roles.AddRange(CodeList.SplitStringToList(dataReader.GetString(6)));
            user.TeamID = dataReader.GetInt32(7);

            return user;
        }


        public static void UpdateUser(User user)
        {
            UpdateUser(user, DBHelper.GetDatabase(), null);
        }
        public static void UpdateUser(User user, TranscationHelper trans)
        {
            UpdateUser(user, trans.DataBase, trans.Transaction);
        }
        private static void UpdateUser(User user, Database db, DbTransaction trans)
        {
            DbCommand dbCommand = db.GetStoredProcCommand("Usp_UpdateSysUser",
                user.ItCode, user.PermLevel, user.Enabled, CodeList.ConvertListToString(user.Roles), user.TeamID);

            try
            {
                if (trans == null)
                    db.ExecuteNonQuery(dbCommand);
                else
                    db.ExecuteNonQuery(dbCommand, trans);
            }
            catch (System.Data.SqlClient.SqlException sex)      // 只捕获SqlException，其余抛出继续传播
            {
                DBHelper.ParseSqlException(sex, false);
            }
        }



        public static int GetUserDynamicRole(string itcode)
        {
            Database db = DBHelper.GetDatabase();

            DbCommand dbCommand = db.GetStoredProcCommand("Usp_GetSysUserDynamicRole", itcode.ToLower());

            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                if (dataReader.Read())
                {
                    return dataReader.GetInt32(0);
                }
            }

            return 0;
        }

    }
}
